package com.citycloud.datac.client.resoult;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class JsonResoult {

	public static void putResponse(ServletRequest servletRequest, ServletResponse servletResponse, long code,
			String errorMsg, String url) throws IOException {
		servletResponse.setCharacterEncoding("utf-8");
		servletResponse.setContentType("application/json;charset=UTF-8");
		OutputStream out = servletResponse.getOutputStream();
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
		String jsonString = getErrorJsonString(code, errorMsg, url);
		pw.println(jsonString);
		pw.flush();
		pw.close();
	}

	/**
	 * 得到错误JSON字符串
	 *
	 * @param code    代码
	 * @param message 消息
	 * @param url     url
	 * @return JSON字符串
	 */
	public static String getErrorJsonString(Long code, String message, String url) {
		String jsonString = "";
		if (message == null) {
			message = "";
		}
		jsonString = "{\"success\":false,\"code\":" + code + ",\"lastTime\":\"" + getDateTimeString(new Date())
				+ "\",\"message\":\"" + message.replace("'", "\\'") + "\",\"url\":\"" + url + "\"}";
		return jsonString;
	}

	/**
	 * 得到日期的字符串 格式为 YYYY-MM-DD HH24:MI:SS
	 *
	 * @param d 日期
	 * @return 日期的字符串
	 */
	public static String getDateTimeString(java.util.Date d) {
		return formatDate(d, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 格式化日期
	 *
	 * @param date   日期
	 * @param format 日期格式
	 * @return 格式化日期
	 */
	public static String formatDate(java.util.Date date, String format) {
		if (format == null || "".equals(format)) {
			format = "yyyy-MM-dd";
		}
		if (date == null) {
			return "";
		} else {
			SimpleDateFormat df = new SimpleDateFormat(format);
			return df.format(date);
		}
	}
}
